module ZepFrog
  module DasPermalinkor
    def self.included(base)
      base.extend Permalinkor
    end
    
    module Permalinkor
      
      def das_permalinked(options = {})
        options[:name] ||= :permalink
        options[:source] ||= :title
        unless included_modules.include? InstanceMethods
          class_inheritable_accessor :options
          extend ClassMethods
          include InstanceMethods
        end
        self.options = options
      end
    end
    
    module ClassMethods
      def permalinked_find(key, *params)
        self.send("find_by_#{options[:name].to_s}".to_sym, key, *params)
      end
    end
    
    module InstanceMethods

      def to_param
        if self.send(options[:name]).nil?
          self.das_permalink = self.send(options[:source]).slugify
          self.save!
        end
        self.send options[:name]
      end
      
      def das_permalink
        unless self.options.nil?
          self.send options[:name]
        else
          self.send :permalink if self.respond_to? :permalink
        end
      end

      def das_permalink=(val)
        unless self.options.nil?
          self[options[:name]] = val
        else
          self.permalink = val if self.respond_to? :permalink
        end
      end

    end
    
  end
end